const { app, BrowserWindow, session, ipcMain } = require('electron');
const path = require('path');
const url = require('url');
const https = require('https');
const http = require('http');

// 保持对window对象的全局引用，避免JavaScript对象被垃圾回收时，窗口被自动关闭
let mainWindow;
ipcMain.handle('gm-xml-http-request', async (event, requestOptions) => {
  const url = new URL(requestOptions.url);
  const client = url.protocol === 'https:' ? https : http;

  const options = {
    protocol: url.protocol,
    hostname: url.hostname,
    port: url.port,
    path: url.pathname + url.search,
    method: requestOptions.method || 'GET',
    headers: requestOptions.headers || {}
  };

  console.log('Request options:', JSON.stringify(options, null, 2));

  return new Promise((resolve) => {
    const req = client.request(options, (res) => {
      let data = '';
      res.setEncoding('utf8');
      res.on('data', chunk => data += chunk);
      res.on('end', () => {
        console.log('Response status:', res.statusCode);
        console.log('Response headers:', res.headers);
        console.log('Response body:', data);
        resolve({
          status: res.statusCode,
          statusText: res.statusMessage,
          responseText: data,
          headers: res.headers
        });
      });
    });

    req.on('error', (err) => {
      console.error('Request error:', err);
      resolve({ error: err.message || err.toString() });
    });

    if (requestOptions.data) {
      console.log('Request data:', requestOptions.data);
      req.write(requestOptions.data);
    }

    req.end();
  });
});


function createWindow() {
  // 创建浏览器窗口
  mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {
      nodeIntegration: false, // 不集成Node.js
      contextIsolation: true, // 启用上下文隔离
      preload: path.join(__dirname, 'preload.js') // 预加载脚本
    }
  });

  // 加载目标URL
  mainWindow.loadURL('https://114.111.61.102/lottery/372');

  // 打开开发者工具
  // mainWindow.webContents.openDevTools();

  // 当window被关闭时，触发下面的事件
  mainWindow.on('closed', function () {
    mainWindow = null;
  });
}

// 当Electron完成初始化并准备创建浏览器窗口时调用此方法
app.whenReady().then(() => {
  createWindow();

  // 注入用户脚本
  mainWindow.webContents.on('did-finish-load', () => {

    const fs = require('fs');
    const GM_xmlhttpRequestPath = path.join(__dirname, 'GM_xmlhttpRequest.js');
    const GM_xmlhttpRequestContent = fs.readFileSync(GM_xmlhttpRequestPath, 'utf8');
    mainWindow.webContents.executeJavaScript(GM_xmlhttpRequestContent)
      .catch(err => console.error('执行用户脚本时出错:', err));

    const userscriptPath = path.join(__dirname, 'userscript.js');
    const userscriptContent = fs.readFileSync(userscriptPath, 'utf8');
    mainWindow.webContents.executeJavaScript(userscriptContent)
      .catch(err => console.error('执行用户脚本时出错:', err));
  });

  app.on('activate', function () {
    // 在macOS上，当dock图标被点击并且没有其他窗口打开时，通常会在应用程序中重新创建一个窗口
    if (mainWindow === null) createWindow();
  });
});

// 当所有窗口都被关闭时退出应用
app.on('window-all-closed', function () {
  // 在macOS上，除非用户用Cmd + Q确定地退出，否则绝大部分应用及其菜单栏会保持激活
  if (process.platform !== 'darwin') app.quit();
});